package com.union.core.sys.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.union.core.organization.dao.impl.PersonnelDaoImpl;
import com.union.core.organization.model.Personnel;
import com.union.core.organization.service.PersonnelService;
import com.union.core.sys.model.Role;
import com.union.core.sys.model.SysManager;
import com.union.core.sys.model.SysModuleType;
import com.union.core.sys.service.RoleService;
import com.union.core.sys.service.SysLogsService;
import com.union.core.sys.service.SysManagerService;
import com.union.core.sys.service.SysService;
import com.opensymphony.xwork2.ActionSupport;

public class SysManagerAction extends ActionSupport{
	private static final long serialVersionUID = 872316002305159L;
	private SysService sysService = SysService.getInstance();

	private SysManagerService sysManagerService;
	
	/*登陆参数*/
	private String LOGIN_NAME;  	//帐号
	private String LOGIN_PWD;		//密码
	private String randCode;		//验证码
	private String loginResult; 	//登陆结果
	
	/*修改密码参数*/
	private String PWD_OLD;
	private String PWD_NEW;
	private String PWD_NEW_CFM;
	private String modifyPwdResult;
	
	/*修改账号密码参数*/
	private String User_log;    //旧登陆账号
	private String User_logcontain;//新登陆账号
	private String Password;//新密码
	private String modifyLogPwd;//返回结果
	

	/*查询列表*/
	private List<SysManager> sysManagerList;
	private SysManager sysManager;
	private int managerId;
	private String[] moduleMgrPurview;
	private int status;
	private List<SysModuleType> sysModuleTypeList;
	private static String moduleName;
	
	//在线人数
	private int onlineUserCount = 0;
	//人员表
	private PersonnelService personSer;
	private List<Personnel> personList;
	private Personnel pers;
	private Personnel personnel;
	private int organizationId;
	private int personnel_id;
	private String orderByName;
	private String paramName;
	private String paramValue;
	private String operaResult;  //反馈结果
	//分配角色
	private String[] roleIds;
	private RoleService roleSer;
	private List<Role> roles;
	private Role role;
	//分页
	private int page;			//页码
	private int intRowCount;	//总行数
	private int intPageCount;	//总页数
	private int start;				//开始
	private int intPageSize=15;	//每页显示的行数
	private int intPage;		//页数变量
	//校验
	private InputStream inputStream;
	//日志
	private SysLogsService logsSer;
	//权限控制
	private List<String> allPower;


	public SysManagerAction(){
		sysManagerService = new SysManagerService();
		personSer=new PersonnelService();
		logsSer = new SysLogsService();
		roleSer= new RoleService();
		personnel = new Personnel();
	}
	
	/**
	 * 登入系统
	 * @return String
	 */
	public String sysLogin(){
		loginResult = sysManagerService.sysManagerLogin(LOGIN_NAME, LOGIN_PWD, randCode);
		if("登陆成功".equals(loginResult)){
			return "SUCCESS";
		}else{
			return "ERROR";
		}
	}
	public String sysLoginLoad(){
		return SUCCESS;
	}
	
	/**
	 * 退出系统
	 * @return
	 */
	public String sysLoginOut(){
		sysService.removeSessionListener();
		return "SUCCESS";
	}
	
	/**
	 * 修改账号密码
	 */
	
	public String modifyUserPwd(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{

			operaResult = sysManagerService.modifySysUser(managerId,User_logcontain,Password); 
			return SUCCESS;
		}
	}
	
	public String modifyUserLoad(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时	
		}else{
			System.out .println("aaaaa"+personnel_id);
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				return SUCCESS;
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
				return "ERR";
			}
		}
	}

	/**
	 * 修改密码
	 * @return
	 */
	public String modifyPwd(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			operaResult = sysManagerService.modifySysManagerPWD(managerId,PWD_OLD,PWD_NEW,PWD_NEW_CFM);
			return SUCCESS;
		}
	}
	public String modifyPwdLoad(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				return SUCCESS;
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
				return "ERR";
			}
		}
	}
	
	/**
	 * 查询
	 * @return String
	 */
	public String list(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			boolean result = sysService.ifHasPurview(moduleName);		
			if(result==true){
				sysManagerList = sysManagerService.queryAll();
				
				onlineUserCount = sysManagerService.getOnlineUserCount();
				
				return "SUCCESS";
			}else{
				return "ERROR";
			}
		}
	}
    
	/**
	 * 添加加载
	 * @return String
	 */
    public String addload() {
    	if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
	    	sysModuleTypeList = sysManagerService.addload();
	    	return "SUCCESS";
		}
    }
	
	/**
	 * 添加
	 * @return String
	 */
    public String add(){
    	if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			boolean result = sysService.ifHasPurview(moduleName);		
			if(result==true){
				sysManagerService.addSysManager(sysManager,moduleMgrPurview);
				return "SUCCESS";
			}else{
				return "ERROR";
			}
		}
    }
	/**
	 * 修改加载
	 * @return String
	 */
    public String editload() {
    	if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
	    	sysManager = sysManagerService.querySysManager(managerId);
	    	sysModuleTypeList = sysManagerService.editload(sysManager.getMODULE_MGR_PURVIEW(),2);
	    	return "SUCCESS";
		}

    }
    /**
     * 修改
     * @return String
     */
    public String edit(){
    	if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			boolean result = sysService.ifHasPurview(moduleName);		
			if(result==true){
				sysManagerService.modifySysManager(sysManager,moduleMgrPurview);
				return "SUCCESS";
			}else{
				return "ERROR";
			}
		}
    }
    
	/**
	 * 删除
	 * @return String
	 */
	public String delete(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			boolean result = sysService.ifHasPurview(moduleName);		
			if(result==true){
				sysManagerService.deleteSysManager(managerId);
				return "SUCCESS";
			}else{
				return "ERROR";
			}
		}
	}
	/**
	 * 修改状态
	 * @return String
	 */
	public String modifySTATUS(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			sysManagerService.modifySysManagerSTATUS(managerId, status);
			sysManagerList = sysManagerService.queryAll();
			return "SUCCESS";
		}
	}
	
	/**
	 * 重置密码
	 * @return String
	 */
	public String resetPwd(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			sysManagerService.resetPwd(managerId, sysManagerService.querySysManager(managerId).getMANAGER_NAME(), "123456");
			sysManagerList = sysManagerService.queryAll();
			return "SUCCESS";
		}
	}
	/**
	 * 加载账户管理
	 */
	public String accountIndex(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
				allPower=sysService.getSessionListener().getAllPower();
				personnel_id=sysService.getSessionListener().getPERSONNEL_ID();
			if(sysService.getSessionListener().getPERSONNEL().getOrganization_id()==1){
				organizationId=1;
				lookForPerson();
			}else{
				if (personnel_id!=0){
					pers=personSer.query(personnel_id);
					organizationId=pers.getOrganization_id();
					lookForPerson();
				}
			}
			return SUCCESS;
		}
	}
	 private void lookForPerson(){
		
		if("".equals(paramName))paramName = null;
		if("".equals(paramValue))paramValue = null;
		if("".equals(orderByName))orderByName = null;
		
		if(page<1){
			intPage = 1;
			page=1;
		}else{
			intPage = page;
		}
		System.out.println("aaaaa"+organizationId);
		personnel = personSer.query1(organizationId);
		String   s = personnel.getChildLst(); 
        String   getChildLst =   "";  
        getChildLst = s.replaceAll( "\\$,","");
        System.out.println("cccc"+getChildLst);
		intRowCount  = personSer.ListCount(0, null, null, null, null, null, null, paramName , paramValue ,0,getChildLst);
		intPageCount = (intRowCount + intPageSize - 1) / intPageSize;
		if(intPage > intPageCount) intPage = intPageCount;		
		if(intPageCount>0){
			start = (intPage-1) * intPageSize;
			personList=personSer.queryList(0, null, null , null , null, null, null, paramName, paramValue, orderByName,
					start, intPageSize, 0,getChildLst);
	    }
	}
	/**
	 * 加载分配账号
	 * */
	public String accountAllotLoad(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			return SUCCESS;
		}
	}

	/**
	 * 分配账号
	 * */
	public String accountAllot(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			int weight=sysService.getSessionListener().getMANAGER_WEIGHT()+1;
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()==0){
				SysManager sysManager= new SysManager();
				sysManager.setMANAGER_NAME(LOGIN_NAME);
				sysManager.setMANAGER_PWD(LOGIN_PWD);
				sysManager.setMANAGER_WEIGHT(weight);
				sysManager.setMODULE_MGR_PURVIEW("");
				sysManager.setMANAGER_DESC(pers.getPersonnel_name());
				sysManager.setPERSONNEL_ID(personnel_id);
				int id=sysManagerService.accountAllot(sysManager);
				if(id!=0){
					pers.setAccount_id(id);
					pers.setAccount_name(sysManager.getMANAGER_NAME());
					boolean bl=personSer.edit(pers);
					if(bl){
						operaResult="恭喜！操作成功。为【"+pers.getPersonnel_name()+"】分配登录账号为："+sysManager.getMANAGER_NAME();
						logsSer.addSysLogs("为【"+pers.getPersonnel_name()+"】分配登录账号为："+sysManager.getMANAGER_NAME());
					}else{
						operaResult="很抱歉！网络故障，操作失败。请稍后再为【"+pers.getPersonnel_name()+"】分配登录账号";
					}
				}else{
					operaResult="很抱歉！网络故障，操作失败。请稍后再为【"+pers.getPersonnel_name()+"】分配登录账号";
				}
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】存在登录账号，请删除后添加！";
			}
			return SUCCESS;
		}
	}
	/**
	 * 删除账号
	 * */
	public String accountDelete(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				//先按account_id删除对应登录账号。把人员表的两个相关字段置空。
				
				sysManagerService.deleteSysManager(pers.getAccount_id());
				pers.setAccount_id(0);
				pers.setAccount_name("");
				boolean bl=personSer.edit(pers);
				if(bl){
					operaResult="恭喜！操作成功。【"+pers.getPersonnel_name()+"】登录账号被删除";
					logsSer.addSysLogs("【"+pers.getPersonnel_name()+"】登录账号被删除");
				}else{
					operaResult="很抱歉！网络故障，操作失败。请稍后再删除【"+pers.getPersonnel_name()+"】的登录账号";
				}
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
			}
			return SUCCESS;
		}
	}
	/**
	 * 加载分配角色
	 * */
	public String roleAllotLoad(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			int orgId=sysService.getSessionListener().getPERSONNEL().getOrganization_id();
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				SysManager sysManager= sysManagerService.querySysManager(pers.getAccount_id());
				roles=sysManagerService.getRoles(sysManager, orgId);
				//返回角色列表，传入sysManager
				return SUCCESS;
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
				return "ERR";
			}
			
		}
	}
	/**
	 * 分配角色
	 * */
	public String roleAllot(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				//分配逻辑，取account_id，将传过来的角色ID数组整成String，加到对应的账号里。
				SysManager sysManager= sysManagerService.querySysManager(pers.getAccount_id());
				boolean bl=sysManagerService.setRoles(sysManager, roleIds);
				if(bl){
					operaResult="恭喜！为【"+pers.getPersonnel_name()+"】分配角色成功。";
					logsSer.addSysLogs("为【"+pers.getPersonnel_name()+"】分配角色");
				}else{
					operaResult="很抱歉！网络故障，操作失败。请稍后再为【"+pers.getPersonnel_name()+"】分配角色";
				}
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
			}
			return SUCCESS;
		}
	}
	/**
	 * 加载用户授权
	 * */
	public String accountEmpowerLoad(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			if(pers.getAccount_id()!=0){
				//判断授权人所拥有的权限
				//授权人用户权限
				String useracl=sysService.getSessionListener().getMODULE_MGR_PURVIEW();
				String roleList=sysService.getSessionListener().getMANAGER_ROLES();
				//授权人角色权限
					//整合授权人角色权限
					Set<String> set = new HashSet<String>();
					
					if(roleList!=null && !"".equals(roleList)){
						for(String rid : roleList.split("\\|")){
							if(!"".equals(rid)){
							role=roleSer.queryById(Integer.parseInt(rid));
							String rpu=role.getRole_permissions();
							if(rpu!=null && !"".equals(rpu)){
								for(String pu : rpu.split("\\|")){
									if(!"".equals(pu)){
										set.add(pu);
									}
								}
							}
						}
						}
					}
					String abc="|";
					//整合授权人用户与角色权限
					if(useracl!=null && !"".equals(useracl)){
						for(String pu : useracl.split("\\|")){
								if(!"".equals(pu)){
									set.add(pu);
								}
							}
					}
					//返回权限
			        for(Object s: set.toArray()){
			        	abc=abc+s.toString()+"|";
			        }
			        sysModuleTypeList=sysManagerService.editload(pers.getAccount_id(), abc);
			        return SUCCESS;
			}else{
				operaResult="【"+pers.getPersonnel_name()+"】未分配登录账号，请先分配账号！";
				return "ERR";
			}
			
		}
	}
	/**
	 * 授予用户权限
	 * */
	public String accountEmpower(){
		if(sysService.ifTimeOut()==false){
			return "TIMEOUT";//超时
		}else{
			pers=personSer.query(personnel_id);
			SysManager sysManager= sysManagerService.querySysManager(pers.getAccount_id());
			boolean bl=sysManagerService.empower(sysManager,moduleMgrPurview);
			
			if(bl){
				operaResult="恭喜！为【"+pers.getPersonnel_name()+"】授权成功。";
				logsSer.addSysLogs("为【"+pers.getPersonnel_name()+"】授权");
			}else{
				operaResult="很抱歉！网络故障，操作失败。请稍后再为【"+pers.getPersonnel_name()+"】授权";
			}
			return SUCCESS;
		}
	}
	/**
	 * 校验登陆用户帐号是否已存在
	 * @param loginName String
	 * @return boolean
	 * false-无记录 true-有记录
	 */
	public String checkLoginName(){
		Boolean canSign = false;
		boolean result = sysManagerService.checkLoginName(LOGIN_NAME);
		if(result==true){//存在,要返回false
			canSign = false;
		}else{
			canSign = true;
		}
		inputStream = new ByteArrayInputStream(canSign.toString().getBytes());
        return SUCCESS;
	}
	public List<Personnel> getPersonList() {
		return personList;
	}

	public void setPersonList(List<Personnel> personList) {
		this.personList = personList;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getIntRowCount() {
		return intRowCount;
	}

	public void setIntRowCount(int intRowCount) {
		this.intRowCount = intRowCount;
	}

	public int getIntPageCount() {
		return intPageCount;
	}

	public void setIntPageCount(int intPageCount) {
		this.intPageCount = intPageCount;
	}

	public String getLOGIN_NAME() {
		return LOGIN_NAME;
	}

	public void setLOGIN_NAME(String login_name) {
		LOGIN_NAME = login_name;
	}

	public String getLOGIN_PWD() {
		return LOGIN_PWD;
	}

	public void setLOGIN_PWD(String login_pwd) {
		LOGIN_PWD = login_pwd;
	}

	public String getRandCode() {
		return randCode;
	}

	public void setRandCode(String randCode) {
		this.randCode = randCode;
	}

	public String getLoginResult() {
		return loginResult;
	}

	public void setLoginResult(String loginResult) {
		this.loginResult = loginResult;
	}

	public String getPWD_OLD() {
		return PWD_OLD;
	}

	public void setPWD_OLD(String pwd_old) {
		PWD_OLD = pwd_old;
	}

	public String getPWD_NEW() {
		return PWD_NEW;
	}

	public void setPWD_NEW(String pwd_new) {
		PWD_NEW = pwd_new;
	}

	public String getPWD_NEW_CFM() {
		return PWD_NEW_CFM;
	}

	public void setPWD_NEW_CFM(String pwd_new_cfm) {
		PWD_NEW_CFM = pwd_new_cfm;
	}

	public String getModifyPwdResult() {
		return modifyPwdResult;
	}

	public void setModifyPwdResult(String modifyPwdResult) {
		this.modifyPwdResult = modifyPwdResult;
	}
	public int getManagerId() {
		return managerId;
	}

	public void setManagerId(int managerId) {
		this.managerId = managerId;
	}

	public String[] getModuleMgrPurview() {
		return moduleMgrPurview;
	}

	public void setModuleMgrPurview(String[] moduleMgrPurview) {
		this.moduleMgrPurview = moduleMgrPurview;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public static String getModuleName() {
		return moduleName;
	}

	public static void setModuleName(String moduleName) {
		SysManagerAction.moduleName = moduleName;
	}

	public List<SysManager> getSysManagerList() {
		return sysManagerList;
	}

	public void setSysManagerList(List<SysManager> sysManagerList) {
		this.sysManagerList = sysManagerList;
	}

	public SysManager getSysManager() {
		return sysManager;
	}

	public void setSysManager(SysManager sysManager) {
		this.sysManager = sysManager;
	}

	public List<SysModuleType> getSysModuleTypeList() {
		return sysModuleTypeList;
	}

	public void setSysModuleTypeList(List<SysModuleType> sysModuleTypeList) {
		this.sysModuleTypeList = sysModuleTypeList;
	}

	public int getOnlineUserCount() {
		return onlineUserCount;
	}

	public void setOnlineUserCount(int onlineUserCount) {
		this.onlineUserCount = onlineUserCount;
	}
	public int getPersonnel_id() {
		return personnel_id;
	}

	public void setPersonnel_id(int personnelId) {
		personnel_id = personnelId;
	}
	public String getOperaResult() {
		return operaResult;
	}

	public void setOperaResult(String operaResult) {
		this.operaResult = operaResult;
	}
	public Personnel getPers() {
		return pers;
	}

	public void setPers(Personnel pers) {
		this.pers = pers;
	}
	public String[] getRoleIds() {
		return roleIds;
	}

	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}

	public List<Role> getRoles() {
		return roles;
	}

	public void setRoles(List<Role> roles) {
		this.roles = roles;
	}
	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	public String getOrderByName() {
		return orderByName;
	}

	public void setOrderByName(String orderByName) {
		this.orderByName = orderByName;
	}

	public String getParamName() {
		return paramName;
	}

	public void setParamName(String paramName) {
		this.paramName = paramName;
	}

	public String getParamValue() {
		return paramValue;
	}

	public void setParamValue(String paramValue) {
		this.paramValue = paramValue;
	}
	public List<String> getAllPower() {
		return allPower;
	}

	public void setAllPower(List<String> allPower) {
		this.allPower = allPower;
	}

	public Personnel getPersonnel() {
		return personnel;
	}

	public void setPersonnel(Personnel personnel) {
		this.personnel = personnel;
	}

	public int getOrganizationId() {
		return organizationId;
	}

	public void setOrganizationId(int organizationId) {
		this.organizationId = organizationId;
	}

	public PersonnelService getPersonSer() {
		return personSer;
	}

	public void setPersonSer(PersonnelService personSer) {
		this.personSer = personSer;
	}

	public String getUser_log() {
		return User_log;
	}

	public void setUser_log(String userLog) {
		User_log = userLog;
	}

	public String getUser_logcontain() {
		return User_logcontain;
	}

	public void setUser_logcontain(String userLogcontain) {
		User_logcontain = userLogcontain;
	}

	public String getPassword() {
		return Password;
	}

	public void setPassword(String password) {
		Password = password;
	}

	public String getModifyLogPwd() {
		return modifyLogPwd;
	}

	public void setModifyLogPwd(String modifyLogPwd) {
		this.modifyLogPwd = modifyLogPwd;
	}

	
	
	
}
